package paidaxing.blog.core.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import paidaxing.blog.common.exception.BusinessException;
import paidaxing.blog.core.dto.SettingDTO;
import paidaxing.blog.core.entity.Settings;
import paidaxing.blog.core.mapper.SettingsMapper;
import paidaxing.blog.core.service.SettingsService;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SettingsServiceImpl implements SettingsService {

    @Resource
    private SettingsMapper settingsMapper;

    @Override
    public List<SettingDTO> getAllSettings() {
        List<Settings> settingsList = settingsMapper.queryAll();
        return settingsList.stream().map(setting -> {
            SettingDTO dto = new SettingDTO();
            BeanUtils.copyProperties(setting, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public String getSettingValue(String settingKey) {
        Settings settings = settingsMapper.queryBySettingKey(settingKey);
        return settings != null ? settings.getSettingValue() : null;
    }

    @Override
    public boolean updateSetting(SettingDTO settingDTO) {
        Settings settings = new Settings();
        BeanUtils.copyProperties(settingDTO, settings);
        settings.setUpdatedAt(new Date());
        
        int result = settingsMapper.update(settings);
        return result > 0;
    }

    @Override
    public boolean createSetting(SettingDTO settingDTO) {
        Settings settings = new Settings();
        BeanUtils.copyProperties(settingDTO, settings);
        settings.setCreatedAt(new Date());
        settings.setUpdatedAt(new Date());
        
        // 检查键名是否已存在
        Settings existingSetting = settingsMapper.queryBySettingKey(settings.getSettingKey());
        if (existingSetting != null) {
            throw new BusinessException("配置键名已存在");
        }
        
        int result = settingsMapper.insert(settings);
        return result > 0;
    }

    @Override
    public boolean deleteSetting(Long id) {
        int result = settingsMapper.deleteById(id);
        return result > 0;
    }
}